package server

import (
	"context"
	"fmt"
	"longmen/server/config/global"
	_const "longmen/server/pkg/common/helper/const"
	time2 "longmen/server/pkg/common/helper/timehelper"
	"longmen/server/pkg/common/helper/util"
	"longmen/server/pkg/db/mysql/db_guess"
	"longmen/server/pkg/db/mysql/models/models_guess"
	pb "longmen/server/pkg/protobuf"
	"strings"
	"time"
)

// 创建一个问题
func (s *Server) CreateQuestion(ctx context.Context, req *pb.CreateQuestionReq) (*pb.CreateQuestionResp, error) {
	fName := "CreateQuestion"
	bHost, err := db_guess.CheckAnchorCanHostGuess(int(req.AnchorId))
	if err != nil {
		return nil, global.LogAndErrorf("%s%v", util.Convert(fName), err.Error())
	}
	if !bHost {
		return nil, global.LogAndErrorf("%s%v", util.Convert(fName), _const.GUESS_ERR_ANCHOR_CANNOT)
	}
	sContent := strings.Replace(req.Content, "｜", "|", -1)
	arrQuestion := strings.Split(sContent, "|")
	if int(req.ItemNum) < 2 || len(arrQuestion) != int(req.ItemNum) { //问题个数不对
		return nil, global.LogAndErrorf("%s%v", util.Convert(fName), _const.GUESS_ERR_WRONG_CONTENT)
	}
	if int(req.MinBet) < 100 { //最小竞猜额小于0
		return nil, global.LogAndErrorf("%s%v", util.Convert(fName), _const.GUESS_ERR_BAD_MIN_BET)
	}
	q := &models_guess.Question{
		CreateTime: time.Now(),
		ItemNum:    int(req.ItemNum),
		Title:      req.Title,
		Content:    req.Content,
		MinBet:     int(req.MinBet),
		MatchId:    int(req.MatchId),
		Status:     _const.QUESTION_STATUS_READY,
		AnchorId:   int(req.AnchorId),
		Comp:       req.Comp,
		MatchTitle: req.MatchTitle,
	}
	id, err := db_guess.InsertQuestion(q)
	if err != nil {
		return nil, global.LogAndErrorf("%s%v", util.Convert(fName), err.Error())
	}
	if id == 0 {
		return nil, fmt.Errorf(_const.GUESS_ERR_UNKNOWN)
	}
	return &pb.CreateQuestionResp{
		QId: int32(id),
		Msg: "ok",
	}, nil
}

// 删除一个问题//只是把状态改为已删除
func (s *Server) DelQuestion(ctx context.Context, req *pb.DelQuestionReq) (*pb.DelQuestionResp, error) {

	mQuery := make(map[string]interface{}, 0)
	if req.QId == 0 {
		return nil, fmt.Errorf("无效的参数q_id")
	} else {
		mQuery["id"] = req.QId
	}
	if req.Uid == 0 {
		return nil, fmt.Errorf("wrong anchor_id")
	} else {
		mQuery["anchor_id"] = req.Uid
	}
	if len(mQuery) == 0 {
		return nil, fmt.Errorf("参数有误")
	}
	o := &models_guess.Question{}
	err := db_guess.GetGuessAnyParam(o, mQuery, true, "delQuestion")
	if err != nil || o.Id == 0 {
		return nil, fmt.Errorf("无效的问题编号")
	} else {
		if o.Status == _const.QUESTION_STATUS_DEL {
			return nil, fmt.Errorf("问题原已删除")
		}
		o.Status = _const.QUESTION_STATUS_DEL
		err = db_guess.UpdateGuessAnyWithId(nil, []string{"status"}, o, "DelQuestion")
		if err != nil {
			return nil, err
		}
	}
	return &pb.DelQuestionResp{
		Msg: "删除成功",
	}, nil

}

// 得问题列表
func (s *Server) GetQuestionList(ctx context.Context, req *pb.GetQuestionListReq) (*pb.GetQuestionListResp, error) {
	var err error
	var n int64
	oQList := make([]*models_guess.Question, 0, 0)
	mQuery := make(map[string]interface{}, 0)

	if req.AnchorId > 0 {
		(mQuery)["anchor_id"] = req.AnchorId
	}

	if req.Status > 0 {
		(mQuery)["status"] = req.Status
	} else {
		(mQuery)["status"] = map[string]interface{}{"!=": []interface{}{_const.QUESTION_STATUS_DEL}}
	}
	if len(req.TEnd) != 0 && len(req.TStart) > 0 {
		if time2.StrToUnix(req.TEnd) == 0 {
			return nil, fmt.Errorf("时间格式有误")
		}
		if time2.StrToUnix(req.TStart) == 0 {
			return nil, fmt.Errorf("时间格式有误")
		}
		mQuery["create_time"] = map[string]interface{}{"between": []interface{}{req.TStart, req.TEnd}}
	}

	if len(mQuery) == 0 {
		return nil, fmt.Errorf("参数有误")
	}

	err = db_guess.GetGuessAnyListParam(&models_guess.Question{}, &oQList, mQuery, "GetQList", "", int(req.Page), int(req.Size))
	if err != nil {
		return nil, err
	}
	err = db_guess.CountGuessAnyParam(&models_guess.Question{}, &n, mQuery, "GetQListCount", "", 0, 0)
	if err != nil {
		return nil, err
	}

	slice := make([]*pb.Question, 0)
	for _, v := range oQList {
		if v.Id > 0 {
			slice = append(slice, &pb.Question{
				Id:         int32(v.Id),
				Content:    v.Content,
				Title:      v.Title,
				MatchId:    int32(v.MatchId),
				ItemNum:    int32(v.ItemNum),
				MinBet:     int32(v.MinBet),
				MatchTitle: v.MatchTitle,
				AnchorId:   int32(v.AnchorId),
				Status:     int32(v.Status),
				CreateTime: v.CreateTime.Format("2006-01-02 15:04:05"),
				Comp:       v.Comp,
				Reason:     v.Reason,
			})
		}
	}
	return &pb.GetQuestionListResp{
		Total:    n,
		Question: slice,
	}, nil

}
